package org.xiaov.lunasql.engine.function;

import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.SQLObject;
import com.alibaba.druid.sql.ast.SQLReplaceable;
import com.alibaba.druid.sql.ast.expr.SQLCaseExpr;
import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr;

import java.util.List;

/**
 * <p>
 * If2CaseWhenFunc
 * </p>
 *
 * @author lzq
 * @since 2024/12/17 20:19
 */
public class If2CaseWhenFunc implements MySqlFunction {
    private final static String METHOD_NAME = "if";

    @Override
    public boolean accept(SQLMethodInvokeExpr methodInvokeExpr) {
        return METHOD_NAME.equalsIgnoreCase(methodInvokeExpr.getMethodName());
    }

    @Override
    public void transform(SQLMethodInvokeExpr methodInvokeExpr) {
        List<SQLExpr> arguments = methodInvokeExpr.getArguments();
        SQLCaseExpr caseExpr = new SQLCaseExpr();
        caseExpr.addItem(arguments.get(0), arguments.get(1));
        caseExpr.setElseExpr(arguments.get(2));

        SQLObject parent = methodInvokeExpr.getParent();
        if (parent instanceof SQLReplaceable replaceable) {
            replaceable.replace(methodInvokeExpr, caseExpr);
        }
    }
}
